<<<<<<< HEAD:audio_feature/util.py
import math
import numpy 
import matplotlib.pyplot as plt
# -------------------------------------------------------------------------
# Conversion Functions
# -------------------------------------------------------------------------

def hz2mel(hz):
	 return 2595* math.log10(1 + hz/700)

def mel2hz(mel):
    freq = 700*(10**(mel/2595)- 1);
    return freq
    
def  hz2bark(freq):
    bark = 13*math.atan(0.00076*freq) + 3.5*math.atan(pow(freq/7500,2));
    return bark

def sinh(d):
    if isinstance (d,numpy.ndarray):	  	
    	  result = numpy.zeros(d.shape[0])
    	  for idx in range(d.shape[0]):
    	  		result[idx]= math.sinh(d[idx])
    else:
	      result = math.sinh(d)
    return result

def abs(d):
    if isinstance (d,numpy.ndarray):	  	
    	  result = numpy.zeros(d.shape[0])
    	  for idx in range(d.shape[0]):
    	  		result[idx]= math.fabs(d[idx])
    else:
	      result = math.fabs(d)
    return result
	  		    
def bark2hz(bark):
    freq = 650*sinh(abs(bark)/7)	  	  
    return freq
    
def hz2erb(hz):
    erb = 21.4*math.log10(0.00437*hz+1);
    return erb
    
def erb2hz(erb):
    hz = (10**(erb/21.4) - 1)/0.00437;
    return hz


def default_params():
    default={
        "Range": [50, 7000],
#        "SampleRate": 16000,
        "NumBands":  40,
        "FFTLength":  512,
#        "WindowLength":400,
#        "OverlapLength":240,
        "WarpType":"mel",
        "WindowType":"hann"
    }
    return  default
# only symmetric is implemented. 
#periodic is not implemented.
def design_window(window_type,win_length):
	N=win_length
	w=numpy.empty([N,1])
	if window_type=="hann":
		  #The following equation generates the coefficients of a Hann window:
      #w(n)=0.5(1-cos(2 PI n/N)),0<=n<=N
      #The window length L = N + 1.
	    for n in range(0,N):
	    	v = 0.5*(1-math.cos(2*math.pi*n/(N-1)))
	    	w[n][0]=v
	elif window_type=="hamming":
	    for n in range(N):  	
	    	v = 0.54 - 0.46*math.cos(2*math.pi*n/(N-1));
	    	w[n][0]=v
	else:
	    raise ValueError("%s not implemented."%window_type)
	return w
  
# only triangle filters  mel and bark filter banks are implemented.  
def design_filter_bank(params):
    low_freq_hz=params.Range[0]
    high_freq_hz=params.Range[1]
    nfilt = params.NumBands
    NFFT = params.FFTLength
    sample_rate = params.SampleRate
    print(sample_rate)    
    if params.WarpType == "mel": 
        low_freq_mel = hz2mel( low_freq_hz)  # Convert Hz to Mel
        high_freq_mel = hz2mel( high_freq_hz)  # Convert Hz to Mel

        mel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2)  # Equally spaced in Mel scale        
        hz_points = mel2hz(mel_points)
        print(low_freq_mel) 
        print(high_freq_mel)
        print(mel_points)
        print(hz_points)


    elif params.WarpType == "bark": 
        low_freq_bark = hz2bark( low_freq_hz)  # Convert Hz to bark
        high_freq_bark = hz2bark( high_freq_hz)  # Convert Hz to bark

        bark_points = numpy.linspace(low_freq_bark, high_freq_bark, nfilt + 2)  # Equally spaced in bark scale        
        hz_points = bark2hz(bark_points)
 
	else:
	    raise ValueError("%s not implemented."%params.WarpType)
		
    bin = numpy.floor((NFFT + 1) * hz_points / sample_rate)
    #print(params.NumBands)
    #print(params.WarpType)
    #print(bin)
    #fbank = numpy.zeros((nfilt, int(numpy.floor(NFFT / 2 + 1))))
    fbank = numpy.zeros([nfilt, NFFT])
    for m in range(1, nfilt + 1):
        f_m_minus = int(bin[m - 1])   # left
        f_m = int(bin[m])             # center
        f_m_plus = int(bin[m + 1])    # right

        bandwidth=hz_points[m+1]-hz_points[m-1]
    
        for k in range(f_m_minus, f_m):
            fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])/bandwidth
        for k in range(f_m, f_m_plus):
            fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])/bandwidth

    pow_frames = 2.0
    filter_banks = numpy.dot(pow_frames,fbank)
    #filter_banks = numpy.where(filter_banks == 0, numpy.finfo(float).eps, filter_banks)  # Numerical Stability
    #filter_banks = 20 * numpy.log10(filter_banks)  # dB
    #print(filter_banks.shape)
    #n = int(numpy.floor(NFFT / 2 + 1))
    #x = numpy.linspace(0,n,n)
    #plt.figure

    #plt.plot(x,fbank.T)
    #plt.show()    
    return filter_banks
      
    
if __name__ =="__main__":
    w = design_window(1,400)
    #print(w)
    w = design_window(2,400)
    #print(w)
    low_freq_hz=50
    high_freq_hz=7000   
    nfilt = 40 
    low_freq_bark = hz2bark( low_freq_hz)  # Convert Hz to bark
    high_freq_bark = hz2bark( high_freq_hz)  # Convert Hz to bark    	  
    bark_points = numpy.linspace(low_freq_bark, high_freq_bark, nfilt + 2)  # Equally spaced in bark scale       
    hz_points = bark2hz(bark_points)
    #print(low_freq_bark) 
    #print(high_freq_bark)
    #print(bark_points)
    #print(hz_points)
    
    low_freq_mel = hz2mel( low_freq_hz)  # Convert Hz to mel
    high_freq_mel = hz2mel( high_freq_hz)  # Convert Hz to mel    	  
    mel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2)  # Equally spaced in mel scale       
    hz_points = mel2hz(mel_points)
    #print(low_freq_mel) 
    #print(high_freq_mel)
    #print(mel_points)
    #print(hz_points)
    
    low_freq_erb = hz2erb( low_freq_hz)  # Convert Hz to erb
    high_freq_erb = hz2erb( high_freq_hz)  # Convert Hz to erb    	  
    erb_points = numpy.linspace(low_freq_erb, high_freq_erb, nfilt + 2)  # Equally spaced in erb scale       
    hz_points = erb2hz(erb_points)
    #print(low_freq_erb) 
    #print(high_freq_erb)
    #print(erb_points)
    #print(hz_points)  
    
    from params import Parameters
    default= default_params()
    params  = Parameters()
    params.set_param(**default)
    filter_bank = design_filter_bank(params)
    #n = int(numpy.floor(filter_bank.shape[1]))
    #X = numpy.linspace(0,n,n)
    #plt.figure          
    #plt.plot(X,filter_bank,'.-','MarkerSize', 10)
    #plt.show()
=======
import math
import numpy


# -------------------------------------------------------------------------
# Conversion Functions
# -------------------------------------------------------------------------

def hz2mel(hz):
	 return 2595* math.log10(1 + hz/700)

def mel2hz(mel):
    freq = 700*(10**(mel/2595)- 1);
    return freq
    
def  hz2bark(freq):
    bark = 13*math.atan(0.00076*freq) + 3.5*math.atan(pow(freq/7500,2));
    return bark

def sinh(d):
    if isinstance (d,numpy.ndarray):	  	
    	  result = numpy.zeros(d.shape[0])
    	  for idx in range(d.shape[0]):
    	  		result[idx]= math.sinh(d[idx])
    else:
	      result = math.sinh(d)
    return result

def abs(d):
    if isinstance (d,numpy.ndarray):	  	
    	  result = numpy.zeros(d.shape[0])
    	  for idx in range(d.shape[0]):
    	  		result[idx]= math.fabs(d[idx])
    else:
	      result = math.fabs(d)
    return result
	  		    
def bark2hz(bark):
    freq = 650*sinh(abs(bark)/7)	  	  
    return freq
    
def hz2erb(hz):
    erb = 21.4*math.log10(0.00437*hz+1);
    return erb
    
def erb2hz(erb):
    hz = (10**(erb/21.4) - 1)/0.00437;
    return hz


def default_params():
    default={
        "Range": [50, 7000],
#        "SampleRate": 16000,
        "NumBands":  40,
        "FFTLength":  512,
#        "WindowLength":400,
#        "OverlapLength":240,
        "WarpType":"mel",
        "WindowType":"hann"
    }
    return  default
# only symmetric is implemented. 
#periodic is not implemented.
def design_window(window_type,win_length):
	N=win_length
	w=numpy.empty([N,1])
	if window_type=="hann":
		  #The following equation generates the coefficients of a Hann window:
      #w(n)=0.5(1-cos(2 PI n/N)),0<=n<=N
      #The window length L = N + 1.
	    for n in range(0,N):
	    	v = 0.5*(1-math.cos(2*math.pi*n/(N-1)))
	    	w[n][0]=v
	elif window_type=="hamming":
	    for n in range(N):  	
	    	v = 0.54 - 0.46*math.cos(2*math.pi*n/(N-1));
	    	w[n][0]=v
	else:
	    raise ValueError("%s not implemented."%window_type)
	return w
  
# only triangle filters  mel and bark filter banks are implemented.  
def design_filter_bank(params):
    low_freq_hz=params.Range[0]
    high_freq_hz=params.Range[1]
    nfilt = params.NumBands
    NFFT = params.FFTLength
    sample_rate = params.SampleRate
    print(sample_rate)    
    if params.WarpType == "mel": 
        low_freq_mel = hz2mel( low_freq_hz)  # Convert Hz to Mel
        high_freq_mel = hz2mel( high_freq_hz)  # Convert Hz to Mel

        mel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2)  # Equally spaced in Mel scale        
        hz_points = mel2hz(mel_points)
        print(low_freq_mel) 
        print(high_freq_mel)
        print(mel_points)
        print(hz_points)


    elif params.WarpType == "bark": 
        low_freq_bark = hz2bark( low_freq_hz)  # Convert Hz to bark
        high_freq_bark = hz2bark( high_freq_hz)  # Convert Hz to bark

        bark_points = numpy.linspace(low_freq_bark, high_freq_bark, nfilt + 2)  # Equally spaced in bark scale        
        hz_points = bark2hz(bark_points)
 
	else:
	    raise ValueError("%s not implemented."%params.WarpType)
		
    bin = numpy.floor((NFFT + 1) * hz_points / sample_rate)
    #print(params.NumBands)
    #print(params.WarpType)
    #print(bin)
    #fbank = numpy.zeros((nfilt, int(numpy.floor(NFFT / 2 + 1))))
    fbank = numpy.zeros([nfilt, NFFT])
    for m in range(1, nfilt + 1):
        f_m_minus = int(bin[m - 1])   # left
        f_m = int(bin[m])             # center
        f_m_plus = int(bin[m + 1])    # right

        bandwidth=hz_points[m+1]-hz_points[m-1]
    
        for k in range(f_m_minus, f_m):
            fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])/bandwidth
        for k in range(f_m, f_m_plus):
            fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])/bandwidth

    pow_frames = 2.0
    filter_banks = numpy.dot(pow_frames,fbank)
    #filter_banks = numpy.where(filter_banks == 0, numpy.finfo(float).eps, filter_banks)  # Numerical Stability
    #filter_banks = 20 * numpy.log10(filter_banks)  # dB
    #print(filter_banks.shape)
    #n = int(numpy.floor(NFFT / 2 + 1))
    #x = numpy.linspace(0,n,n)
    #plt.figure

    #plt.plot(x,fbank.T)
    #plt.show()    
    return filter_banks
      
    
if __name__ =="__main__":
    w = design_window(1,400)
    #print(w)
    w = design_window(2,400)
    #print(w)
    low_freq_hz=50
    high_freq_hz=7000   
    nfilt = 40 
    low_freq_bark = hz2bark( low_freq_hz)  # Convert Hz to bark
    high_freq_bark = hz2bark( high_freq_hz)  # Convert Hz to bark    	  
    bark_points = numpy.linspace(low_freq_bark, high_freq_bark, nfilt + 2)  # Equally spaced in bark scale       
    hz_points = bark2hz(bark_points)
    #print(low_freq_bark) 
    #print(high_freq_bark)
    #print(bark_points)
    #print(hz_points)
    
    low_freq_mel = hz2mel( low_freq_hz)  # Convert Hz to mel
    high_freq_mel = hz2mel( high_freq_hz)  # Convert Hz to mel    	  
    mel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2)  # Equally spaced in mel scale       
    hz_points = mel2hz(mel_points)
    #print(low_freq_mel) 
    #print(high_freq_mel)
    #print(mel_points)
    #print(hz_points)
    
    low_freq_erb = hz2erb( low_freq_hz)  # Convert Hz to erb
    high_freq_erb = hz2erb( high_freq_hz)  # Convert Hz to erb    	  
    erb_points = numpy.linspace(low_freq_erb, high_freq_erb, nfilt + 2)  # Equally spaced in erb scale       
    hz_points = erb2hz(erb_points)
    #print(low_freq_erb) 
    #print(high_freq_erb)
    #print(erb_points)
    #print(hz_points)  
    
    from tests.params import Parameters
    default= default_params()
    params  = Parameters()
    params.set_param(**default)
    filter_bank = design_filter_bank(params)
    #n = int(numpy.floor(filter_bank.shape[1]))
    #X = numpy.linspace(0,n,n)
    #plt.figure          
    #plt.plot(X,filter_bank,'.-','MarkerSize', 10)
    #plt.show()
>>>>>>> 4eba858 (bug fix and add test scripts):tests/util.py
